import { formItemLayout } from '@/support/constant/common';
import Icon, { PlusOutlined } from '@ant-design/icons';
import {
  Form,
  Input,
  Modal,
  Upload,
  FormProps,
  FormItemProps,
  ModalProps,
  message,
  Col,
  Tooltip,
} from 'antd';
import React, { useState } from 'react';
import { getMd5, getToken } from '@/utils/utils';
import { windowUrl } from '../../../../public/global';
import { getOptAuthHeaders } from '@/utils/common';

type IProps = ModalProps & {
  formProps: FormProps;
  formItemPorps?: FormItemProps;
  fieldsList: any[];
  disabled?: boolean;
};

const FormItem = Form.Item;
const { TextArea } = Input;

const uploadUrl = '/upload/single?bizType=m18';
const url = `${windowUrl}${uploadUrl}`;
let md5 = getMd5('bizType=m18');

const AddDirModal = (props: IProps) => {
  const { formProps, fieldsList, disabled, ...modalProps } = props;

  const [fileList, setFileList] = useState([]);
  const [uploadFinished, setUploadFinished] = useState<boolean>(true);
  const generateTempItem = (data, name) => {
    const { type } = data;
    switch (`${type}`) {
      // 文本
      case '1': {
        const { type, _id, isRequire, isMutilate, length, key, labelName } = data;
        const placeholder = `请输入${labelName || ''}`;
        return (
          <>
            <Col span={24} key={name}>
              <FormItem
                {...formItemLayout}
                key={_id}
                label={labelName}
                rules={[{ required: isRequire === 1, message: `请输入文本` }]}
                name={[name, 'content']}
                required
              >
                {isMutilate === 1 ? (
                  <TextArea
                    rows={4}
                    placeholder={placeholder}
                    autoComplete="off"
                    allowClear
                    disabled={disabled}
                    maxLength={length}
                  />
                ) : (
                  <Input
                    placeholder={placeholder}
                    autoComplete="off"
                    allowClear
                    disabled={disabled}
                    maxLength={length}
                  />
                )}
              </FormItem>
            </Col>
          </>
        );
      }
      // 图片
      case '3': {
        const {
          type,
          _id,
          isRequire,
          isMutilate,
          length,
          width,
          format,
          graphics,
          size,
          content,
          level,
          key,
          labelName,
          disabled,
          catalogueName,
        } = data;
        const uploadButton = (
          <div>
            <PlusOutlined style={{ fontSize: 24 }} />
            <div style={{ marginTop: 8 }}>上传照片</div>
          </div>
        );
        const beforeUpload = file => {
          const currentFileType = file.name.substring(file.name.lastIndexOf('.')); //解析文件名后缀
          const isJpgOrPng = format ? format.split(';').indexOf(currentFileType) > -1 : true;
          if (!isJpgOrPng) {
            message.error('请上传规定格式图片');
          }
          const isMaxSize = size ? file.size / 1024 / 1024 > size : false;
          if (isMaxSize) {
            message.error(`图片大小不超过${size}Mb`);
          }
          return (isJpgOrPng && !isMaxSize) || Upload.LIST_IGNORE;
        };

        const handleChange = (info: any) => {
          let { fileList, file } = info;
          console.log(fileList, file);
          setUploadFinished(false);
          if (file.status === 'done' && file.response && file.response.responseCode === '200') {
            setUploadFinished(true);
            message.success(`${file.name} 上传成功`);
            let newFileList = fileList.map(
              (item: { response: any; uid: any; status: any; name: any; url: any }) => {
                return {
                  uid: item.uid,
                  status: item.status,
                  name: item.name,
                  // url: item.response?.fileRecordList[0]?.fileUri,
                  url: item.response ? item.response.fileRecordList[0]?.fileUri : item.url,
                };
              },
            );
            setFileList(newFileList);
            formProps.form?.setFieldValue(['contents', name, 'content'], newFileList);
          } else if (
            file.status === 'done' &&
            file.response &&
            file.response.responseCode !== '200'
          ) {
            setUploadFinished(true);
            message.error(file.response.responseMsg);
            // this.setState({ fileList: [] });
            fileList = fileList.slice(0, -1);

            // return;
          } else if (file.status === 'removed') {
            setUploadFinished(true);
            message.success('删除成功');
          } else if (file.status === 'error') {
            message.error(`${file.name} 上传失败`);
            setUploadFinished(true);
            fileList = fileList.slice(0, -1);
            // console.log(fileList);
            // return;
          } else if (!file.status) {
            setUploadFinished(true);
            fileList = fileList.slice(0, -1);
            message.error(`${file.name} 上传失败`);
            // return;
          }
        };

        const normFile = (e: any) => {
          console.log('Upload event:--------', e);
          if (Array.isArray(e)) {
            return e;
          }
          return e?.fileList;
        };

        return (
          <>
            <Col span={24} key={name}>
              <FormItem
                {...formItemLayout}
                name={[name, 'content']}
                label={labelName}
                rules={[{ required: isRequire === 1, message: `请上传图片` }]}
              >
                <Upload
                  action={url}
                  listType="picture-card"
                  multiple={false}
                  headers={{
                    OptAuthorization: `${getToken()}`,
                    ...getOptAuthHeaders(),
                    shaSign: md5,
                  }}
                  beforeUpload={beforeUpload}
                  onChange={handleChange}
                >
                  {fileList.length && graphics && fileList.length >= graphics ? null : uploadButton}
                </Upload>
                {!disabled && (
                  <span>
                    {format && '只支持' + format + ' 格式，'}
                    {length && width && '尺寸大小为：' + length + '*' + width + '，'}
                    {graphics && '最多上传' + graphics + ' 张图片，'}
                    {size && '图片大小不超过' + size + ' MB'}
                  </span>
                )}
              </FormItem>
            </Col>
            <Col span={24}></Col>
          </>
        );
      }
    }
  };

  return (
    <Modal {...modalProps} okText={'保存'} width={700}>
      <Form {...formProps} {...formItemLayout}>
        <Form.Item
          label="目录名称"
          name="catalogueName"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input placeholder="目录名称" allowClear />
        </Form.Item>
        <Form.List name="contents">
          {fields => (
            <>
              {fields.map(field => {
                return generateTempItem(fieldsList[field.name], field.key);
              })}
            </>
          )}
        </Form.List>
      </Form>
    </Modal>
  );
};

export default AddDirModal;
